import { Effect } from 'dva';
import { Reducer } from 'redux';

import {
  queryList,
  addContentItem,
  editContentItem,
  delContentItem,
  queryTempList,
  queryTagList,
  queryKeyList,
  addTempItem,
  editTempItem,
  delTempItem,
  queryTempContentList,
  queryAudienceList,
  addTempContentItem,
  editTempContentItem,
  sortTempContentItem,
  delTempContentItem,
  queryTempContentSortableList,
  publishTempContentItem
} from '@/services/contentMng';

export interface ContentItem {
  projectId?: string; // 项目id
  contentItemName?: string; // 内容项名称
  contentDescription?: string; // 内容项描述
  createTime?: number | Date; // 创建时间
  createBy?: string; // 创建人
  [key: string]: any;
}

/**
 * 模板
 */
export interface ContentTempItem {
  projectId?: string; // 项目id
  templateCode?: string; // 模板编码
  templateName?: string; // 模板名称
  displayTerminalCode?: number; // 展现终端编号，1：手机；2：车机
  touchWayCode?: number; // 触达方式编号，1：接口；2：推送；3：邮件；4短信：
  contentformStr?: string; // 内容形式
  labelContent?: string; // 标签内容
  templateConfig?: string; // 模板配置json串
  contentDescription?: string; // 内容项描述
  createTime?: number | Date; // 创建时间
  createBy?: string; // 创建人
  updateTime?: number | Date; // 更新时间
  updateBy?: string; // 更新人
  hasPublished?: number; // 包含的内容是否全部没有发布 0：否 1：是
  [key: string]: any;
}
/**
 * 模板对应内容
 */
export interface TempContentItem {
  sid?: string; // 业务主键id
  templateSid?: string; // 模板id
  projectId?: string; // 项目id
  imageUrl?: string; // 图片url
  contentName?: string; // 内容名称
  audienceSid?: string; // 受众对象id
  audienceName?: string; // 受众对象名称
  releaseState?: string; // 发布状态编码
  releaseTime?: string | Date; // 发布时间
  updateTime?: string | Date; // 更新时间
  unreleaseTime?: string | Date; // 下架时间
  publishBy?: string; // 发布人
  unPublishBy?: string; // 下架人
  applyCount?: number; // 内容阅读或下载的次数
  groupSize?: number; // 每组图片的数量
  contentJson?: string; // 对应模板的内容json串
  [key: string]: any;
}
/**
 * 标签项
 */
export interface LabelItem {
  label?: string;
  value?: string;
  [key: string]: any;
}
export interface ContentModelState {
  contentData?: {
    contentList: Array<ContentItem>;
    pagination: { pageSize: number; current: number };
  };
  contentItem?: ContentItem;
  contentTempData?: {
    contentTempList: Array<ContentTempItem>;
    pagination: { pageSize: number; current: number };
  };
  contentTempItem?: ContentTempItem;
  labelList: Array<LabelItem>;
  keyList: Array<any>;
  tempContentData?: {
    tempContentList: Array<TempContentItem>;
    pagination: { pageSize: number; current: number };
  };
  audienceList?: Array<any>;
  allPublishedContentList?: Array<any>;
  tempContentItem?: TempContentItem;
  [key: string]: any;
}

export interface ContentModelType {
  namespace: 'contentMng';
  state: ContentModelState;
  effects: {
    queryList: Effect;
    addContentItem: Effect;
    editContentItem: Effect;
    delContentItem: Effect;
    queryTempList: Effect;
    queryTagList: Effect;
    queryKeyList: Effect;
    addTempItem: Effect;
    editTempItem: Effect;
    delTempItem: Effect;
    queryTempContentList: Effect;
    queryAudienceList: Effect;
    getAllPublishedContent: Effect;
    addTempContent: Effect;
    editTempContent: Effect;
    publishTempContent: Effect;
    sortTempContent: Effect;
    delTempContent: Effect;
  };
  reducers: {
    save: Reducer<ContentModelState>;
  };
}

const ContentModel: ContentModelType = {
  namespace: 'contentMng',
  state: {
    contentData: {
      contentList: [],
      pagination: {
        pageSize: 10,
        current: 1,
      },
    }, // 内容项列表
    contentItem: {},
    contentTempData: {
      contentTempList: [],
      pagination: {
        pageSize: 10,
        current: 1,
      },
    },
    contentTempItem: {},
    labelList: [],
    keyList: [],
    tempContentData: {
      tempContentList: [],
      pagination: {
        pageSize: 10,
        current: 1,
      },
    },
    audienceList: [],
    allPublishedContentList: [],
    tempContentItem: {},
    response: {},
  },

  effects: {
    /**
     * 内容项分页查询
     * @param _
     * @param param
     */
    *queryList({ payload, callback }, { call, put }) {
      if (payload?.current) {
        payload.current = payload.current - 1;
      }
      const response = yield call(queryList, { current: 0, pageSize: 10, ...payload });
      // if (response.statusCode === '0') {
      const { total = 0, current = 0, pageSize = 10 } = response.data?.pagination || {};
      const pageData = {
        current: current + 1,
        pageSize,
        total,
      };
      yield put({
        type: 'save',
        payload: {
          contentData: { contentList: response.data?.list || [], pagination: pageData },
        },
      });
      if (callback) callback(response.data);
      // }
    },
    /**
     * 内容项新增
     * @param param0
     * @param param1
     */
    *addContentItem({ payload, callback }, { call, put }) {
      const response = yield call(addContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 内容项编辑
     * @param param0
     * @param param1
     */
    *editContentItem({ payload, callback }, { call, put }) {
      const response = yield call(editContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 内容项删除
     * @param param0
     * @param param1
     */
    *delContentItem({ payload, callback }, { call, put }) {
      const response = yield call(delContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 内容模板分页查询
     * @param _
     * @param param
     */
    *queryTempList({ payload, callback }, { call, put }) {
      if (payload?.current) {
        payload.current = payload.current - 1;
      }
      const response = yield call(queryTempList, { current: 0, pageSize: 10, ...payload });
      if (response.statusCode === '0') {
        const { total = 0, current = 0, pageSize = 10 } = response.data.pagination;
        const pageData = {
          current: current + 1,
          pageSize,
          total,
        };
        yield put({
          type: 'save',
          payload: {
            contentTempData: { contentTempList: response.data?.list, pagination: pageData },
          },
        });
        if (callback) callback(response.data);
      }
    },
    /**
     * 获取标签
     * @param _
     * @param param
     */
    *queryTagList({ payload, callback }, { call, put }) {
      const response = yield call(queryTagList, payload);
      if (response.statusCode === '0') {
        yield put({
          type: 'save',
          payload: {
            labelList: response.data?.map(item => {
              return {
                label: item,
                value: item,
              };
            }),
          },
        });
        if (callback) callback(response.data);
      }
    },
    /**
     * 获取key列表
     * @param _
     * @param param
     */
    *queryKeyList({ payload, callback }, { call, put }) {
      const response = yield call(queryKeyList, payload);
      if (response.statusCode === '0') {
        yield put({
          type: 'save',
          payload: {
            keyList: Object.keys(response.data).map(key => {
              return {
                label: response.data[key],
                value: key,
              };
            }),
          },
        });
        if (callback) callback(response.data);
      }
    },
    /**
     * 内容模板新增
     * @param param0
     * @param param1
     */
    *addTempItem({ payload, callback }, { call, put }) {
      const response = yield call(addTempItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 内容模板编辑
     * @param param0
     * @param param1
     */
    *editTempItem({ payload, callback }, { call, put }) {
      const response = yield call(editTempItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 内容模板删除
     * @param param0
     * @param param1
     */
    *delTempItem({ payload, callback }, { call, put }) {
      const response = yield call(delTempItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 内容分页查询
     * @param _
     * @param param
     */
    *queryTempContentList({ payload, callback }, { call, put }) {
      if (payload?.current) {
        payload.current = payload.current - 1;
      }
      const response = yield call(queryTempContentList, { current: 0, pageSize: 10, ...payload });
      if (response.statusCode === '0') {
        const { total = 0, current = 0, pageSize = 10 } = response.data.pagination;
        const pageData = {
          current: current + 1,
          pageSize,
          total,
        };
        yield put({
          type: 'save',
          payload: {
            tempContentData: {
              tempContentList: response.data?.list,
              pagination: pageData,
            },
          },
        });
        if (callback) callback(response.data);
      }
    },
    /**
     * 获取所有已发布内容列表
     * @param _
     * @param param
     */
    *getAllPublishedContent({ payload, callback }, { call, put }) {
      const response = yield call(queryTempContentSortableList, { ...payload });
      if (response.statusCode === '0') {
        yield put({
          type: 'save',
          payload: {
            allPublishedContentList: response.data,
          },
        });
        if (callback) callback(response.data);
      }
    },
    /**
     * 受众对象查询
     * @param _
     * @param param
     */
    *queryAudienceList({ payload, callback }, { call, put }) {
      const response = yield call(queryAudienceList, payload);
      if (response.statusCode === '0') {
        yield put({
          type: 'save',
          payload: {
            audienceList: response.data,
          },
        });
        if (callback) callback(response.data);
      }
    },
    /**
     * 模板对应内容新增
     * @param param0
     * @param param1
     */
    *addTempContent({ payload, callback }, { call, put }) {
      const response = yield call(addTempContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 模板对应内容编辑
     * @param param0
     * @param param1
     */
    *editTempContent({ payload, callback }, { call, put }) {
      const response = yield call(editTempContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 模板对应内容发布
     * @param param0
     * @param param1
     */
    *publishTempContent({ payload, callback }, { call, put }) {
      const response = yield call(publishTempContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 模板对应内容排序
     * @param param0
     * @param param1
     */
    *sortTempContent({ payload, callback }, { call, put }) {
      const response = yield call(sortTempContentItem, payload.list);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
    /**
     * 模板对应内容删除
     * @param param0
     * @param param1
     */
    *delTempContent({ payload, callback }, { call, put }) {
      const response = yield call(delTempContentItem, payload);
      if (response.statusCode === '0') {
        yield put({ type: 'save', payload: { data: response } });
        if (callback) callback(response);
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default ContentModel;
